package com.catazy.album.data.datasource.api.model

import com.catazy.album.data.datasource.database.model.AlbumEntityModel
import com.catazy.album.domain.model.Album
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
internal data class AlbumApiModel(
    @SerialName("mbid") val mbId: String? = null,
    @SerialName("name") val name: String,
    @SerialName("artist") val artist: String,
    @SerialName("image") val images: List<ImageApiModel>? = null,
    @SerialName("tracks") val tracks: TrackListApiModel? = null,
    @SerialName("tags") val tags: TagListApiModel? = null,
)

/**
 * 将AlbumApiModel实例转换为AlbumEntityModel实体模型。
 * 此函数主要用于数据层到实体层的转换，确保数据在存储或进一步处理前格式一致。
 *
 * @return 转换后的AlbumEntityModel实例。
 */
internal fun AlbumApiModel.toEntityModel() =
    AlbumEntityModel(
        mbId = this.mbId ?: "",
        name = this.name,
        artist = this.artist,
        images = this.images?.mapNotNull { it.toEntityModel() } ?: listOf(),
        tracks = this.tracks?.track?.map { it.toEntityModel() },
        tags = this.tags?.tag?.map { it.toEntityModel() },
    )

/**
 * 将AlbumApiModel实例转换为Album领域模型。
 * 过滤掉未知或空白URL的图片，确保数据在业务逻辑层的准确性和可用性。
 *
 * @return 转换后的Album领域模型实例。
 */
internal fun AlbumApiModel.toDomainModel(): Album {
    // 过滤并转换图片列表，忽略未知大小或URL为空白的图片。
    val images = this.images
        ?.filterNot { it.size == ImageSizeApiModel.UNKNOWN || it.url.isBlank() }
        ?.map { it.toDomainModel() }

    return Album(
        mbId = this.mbId,
        name = this.name,
        artist = this.artist,
        images = images ?: listOf(),
        tracks = this.tracks?.track?.map { it.toDomainModel() },
        tags = this.tags?.tag?.map { it.toDomainModel() },
    )
}

